package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.entity.Response;
import com.entity.pojo.LfCase;
import com.mapper.LfCaseMapper;
import com.service.UserService;
import com.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/case")
public class CaseController {

    @Resource
    private LfCaseMapper lfCaseMapper;

    @Resource
    private UserService userService;

    @GetMapping
    public Response listCase() {
        List<LfCase> list = lfCaseMapper.selectList(new QueryWrapper<LfCase>().eq("deleted", 0));
        return new Response().setSuccess().appendMsg("list", list);
    }

    @GetMapping("/my")
    public Response listMyCase() {
        Subject subject = SecurityUtils.getSubject();
        String username = JwtUtil.getUuid((String) subject.getPrincipal());
        Integer userId = userService.getUser(username).getId();
        List<LfCase> list = lfCaseMapper.selectList(new QueryWrapper<LfCase>().eq("deleted", 0).eq("user_id", userId));
        return new Response().setSuccess().appendMsg("list", list);
    }


    @PostMapping
    public Response insertCase(@RequestBody LfCase lfCase) {
        Subject subject = SecurityUtils.getSubject();
        String username = JwtUtil.getUuid((String) subject.getPrincipal());
        Integer userId = userService.getUser(username).getId();
        int res = lfCaseMapper.insert(lfCase.setUserId(userId).setCreateTime(LocalDateTime.now()));
        if (res > 0) {
            return new Response().setSuccess();
        } else {
            return new Response().setFailed().setErrMsg("操作失败");
        }
    }

    @PutMapping
    public Response updateCase(@RequestBody LfCase lfCase) {
        int res = lfCaseMapper.updateById(lfCase.setUpdateTime(LocalDateTime.now()));
        if (res > 0) {
            return new Response().setSuccess();
        } else {
            return new Response().setFailed().setErrMsg("操作失败");
        }
    }

}
